package service

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
)

/**
 * Author: ycliud
 * Description: 登录
 * Date:20250927
 */
type LoginService struct {
	db *CmsApp
}

type LoginReq struct {
	UserID   string `json:"user_id" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type LoginRsp struct {
	SessionID string `json:"session_id"`
	UserID    string `json:"user_id"`
	Nickname  string `json:"nickname"`
	Message   string `json:"message"`
}

func (c *LoginService) Login(ctx *gin.Context) {
	//span := opentracing.SpanFromContext(ctx.Request.Context())
	var req LoginReq
	cmsApp := NewCmsApp()
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	ctx.ShouldBindJSON(&req)
	//
	fmt.Println(req.UserID)
	fmt.Println(req.Password)
	//span.SetTag("req", req)
	var (
		userID = req.UserID
	)
	accountDao := NewAccountDao(cmsApp.db)
	account, err := accountDao.FirstByUserID(ctx.Request.Context(), userID)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "请输入正确的账号ID"})
		return
	}
	/*if err := bcrypt.CompareHashAndPassword(
		[]byte(account.Password),
		[]byte(password)); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "请输入正确的密码"})
		return
	}*/
	/*	sessionID, err := c.generateSessionID(ctx.Request.Context(), userID)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"error": "系统错误，请稍后重试"})
			return
		}*/
	// 回包
	ctx.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"msg":  "ok",
		"data": &LoginRsp{
			UserID:   account.UserID,
			Nickname: account.Nickname,
			Message:  fmt.Sprintf("登录成功"),
		},
	})
	return
}
